package cn.zl.ssoserver.interceptor;

import cn.zl.ssoserver.constant.ServerConstant;
import cn.zl.ssoserver.util.SsoCookieUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @Description:配置拦截器
 * @Author: zllwsy
 * @Date: 2020/11/4 10:19
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws Exception{
        //客户端唯一标识uuid，客户端第一次访问时的session作为唯一标识，如果为空则写入cookie中
        HttpSession session = request.getSession();
        String uuid = SsoCookieUtil.getCookie(request, "uuid");
        if (StringUtils.isEmpty(uuid)){
            //如果uuid为空，则将session的id设置为uuid
            uuid = session.getId();
            //将uuid存储到cookie中
            SsoCookieUtil.setDomainCookie(response,"uuid",uuid,3600);
        }
        //从cookie中获取ticket
        String ticket = SsoCookieUtil.getCookie(request, "ticket");
//        String ticket = null;
//        if (aesDecode != null){
//            ticket = EncryptUtil.AESDecode(aesDecode);
//        }

        //如果cookie中没有获取到，则从请求中去获取
        if (StringUtils.isEmpty(ticket)){
//            String oldTicketValue = redisTemplate.opsForValue().get(ServerConstant.REDIS_TICKET_PREFIX + ticket);
//            System.out.println(oldTicketValue);
            ticket = request.getParameter("ticket");
        }
        //如果ticket为空
        if (StringUtils.isEmpty(ticket)){
            logger.debug("非法请求：未获取到ticket，重定向到登录页面...");
            //由于没有ticket，就重定向认证服务的登录接口
            response.sendRedirect(ServerConstant.SSO_URL + "loginPage?originalUrl=" + request.getRequestURL() + "&uuid=" + uuid);
//            String s = Contstant.SSO_URL + "loginPage?originalUrl=" + request.getRequestURL() + "&uuid=" + uuid;
//            System.out.println(s);
            return false;
        }else {
            RestTemplate restTemplate = new RestTemplate();
            //验证ticket,校验成功返回ticket，实际上校验成功时可以返回用户信息，校验失败则返回null
            String t = restTemplate.getForObject(ServerConstant.SSO_URL + "checkTicket?ticket=" + ticket + "&uuid=" + uuid, String.class);
            if (t != null){
                //通过restTemplate来发送内部http请求，获取用户信息，然后存储到map中
                Map userInfo = restTemplate.getForObject(ServerConstant.SSO_URL + "getUserInfo?ticket=" + t, Map.class);
                logger.debug("ticket验证通过：",userInfo);
                //userInfo存入到session中
                session.setAttribute("userInfo",userInfo);
                //更新ticket
//                String aesEncode = EncryptUtil.AESEncode(ticket);
//                CookieUtil.setCookie(response,"aesEncode",t,60);
                SsoCookieUtil.setDomainCookie(response,"ticket",t,60);

            }else {
                logger.debug("非法请求：路径错误，重定向到登录页面...");
                response.sendRedirect(ServerConstant.SSO_URL + "loginPage?originalUrl=" + request.getRequestURL() + "&uuid=" + uuid);
                return false;
            }
        }
        return true;
    }
}
